package com.demo.Controller;

import com.demo.Configuration.JdbcConfiguration;
import com.demo.Model.Cj;
import com.demo.Model.Login;
import com.demo.Model.SessionMap;
import com.demo.Model.User;
import com.demo.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    JdbcConfiguration jdbcConfiguration;

    @Autowired
    UserService userService;

    ArrayList al = new ArrayList();

    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "hello world!";
    }

    @RequestMapping("/test2")
    public String test2(Model model){
        String a1 = "hello world2";
        model.addAttribute("aa", a1);
        return "test";
    }

    @RequestMapping("/test3")
    @ResponseBody
    public String test3() throws ClassNotFoundException, SQLException {
        String url= "jdbc.mysql://localhost:3306/wg12?useCursorFetch=true&amp;autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8";
        String username = "root";
        String password = "223344";
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url, username, password);
        return "连接成功";
    }

    @RequestMapping("/list2")
    public String list(Model model){
        User user = new User();
        user.setId(1);
        user.setName("张三");
        user.setAge(20);
        user.setGender("男");
        ArrayList<User> al = new ArrayList<User>();
        User user2 = new User();
        user2.setId(2);
        user2.setName("李四");
        user2.setGender("女");
        user2.setAge(21);
        al.add(user);
        al.add(user2);
        model.addAttribute("users", al);
        return "list";
    }

    @RequestMapping("/test4")
    public String test4(Model model) throws ClassNotFoundException, SQLException {
        String url= "jdbc:mysql://localhost:3306/wg12?useCursorFetch=true&amp;autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8";
        String username = "root";
        String password = "223344";
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url, username, password);
        System.out.println("连接成功");

        Statement st = conn.createStatement();
        String sql = "select * from users";
        ResultSet rs = st.executeQuery(sql);
        User[] user = new User[5];
        int i=0;
        while(rs.next()){
            User user1 = new User();
            user1.setId(rs.getInt("id"));
            user1.setName(rs.getString("name"));
            user1.setGender(rs.getString("gender"));
            user1.setAge(rs.getInt("age"));
            user[i] = user1;
            i++;
        }
        model.addAttribute("users", user);
        return "list";
    }
    @RequestMapping("/list")
    public String query(Model model, HttpSession session){
        List<User> users = userService.query();
        model.addAttribute("users", users);
        List<Login> login = (List<Login>)session.getAttribute("login");
        Integer count =(Integer) session.getServletContext().getAttribute("count");
        String name = login.get(0).getName();
        model.addAttribute("name", name);
        model.addAttribute("count", count);
        return "list";
    }

    @RequestMapping("/del")
    public String del(int id){
        userService.deleteById(id);
        return "redirect:list";
    }

    @RequestMapping("/add")
    public String add(){
        return "add";
    }

    @RequestMapping("/add_save")
    public String add_save(User user){
        userService.insert(user);
        return "redirect:list";
    }

    @RequestMapping("/update")
    public String queryById(int id, Model model){
        List<User> users = userService.queryById(id);
        model.addAttribute("users", users);
        return "update";
    }

    @RequestMapping("/update_save")
    public String update_save(User user){
        userService.updateById(user);
        return "redirect:list";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

//    @RequestMapping("/log")
//    public String log(Integer xh, String password, Model model,
//                      HttpSession session) {
//        if (xh == null) {
//            model.addAttribute("mess", "账号不能为空");
//            return "login";
//        } else if (password == null || "".equals(password)) {
//            model.addAttribute("mess", "密码不能为空");
//            return "login";
//        } else {
//            List<Login> login = userService.log(xh, password);
//            if (login.size() > 0) {
//                if(!al.contains(xh)) {
//                    al.add(xh);
//                    String name = login.get(0).getName();
//                    session.setAttribute("login", login);
//                    session.setMaxInactiveInterval(120);
//                    return "redirect:list";
//                }else{
//                    model.addAttribute("mess", "账号已在其他地方登陆");
//                    return "login";
//                }
//            } else {
//                model.addAttribute("mess", "用户名或密码错误");
//                return "login";
//            }
//        }
//    }

    @RequestMapping("/log")
    public String log(Integer xh, String password, Model model,
                      HttpServletRequest request) {
        if (xh == null) {
            model.addAttribute("mess", "账号不能为空");
            return "login";
        } else if (password == null || "".equals(password)) {
            model.addAttribute("mess", "密码不能为空");
            return "login";
        } else {
            List<Login> login = userService.log(xh, password);
            if (login.size() > 0) {
                    boolean logined = userService.checkLogined(xh);
                    if(logined) {
                        HttpSession session1 = (HttpSession) SessionMap.sessionMap.get(String.valueOf(xh));
                        session1.removeAttribute("login");
                    }
                    String name = login.get(0).getName();
                    SessionMap.sessionMap.put(String.valueOf(xh), request.getSession());
                    request.getSession().setAttribute("login", login);
                    request.getSession().setMaxInactiveInterval(120);
                    return "redirect:list";

            } else {
                model.addAttribute("mess", "用户名或密码错误");
                return "login";
            }
        }
    }

    @RequestMapping("/cj")
    public String cj(HttpServletRequest request, Model model){
        List<Login> login = (List<Login>) request.getSession().getAttribute("login");
        int xh = login.get(0).getXh();
        List<Cj> cj = userService.queryCj(xh);
        model.addAttribute("cjs", cj);
        return "cj";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        List<Login> login = (List<Login>) session.getAttribute("login");
        al.remove(login.get(0).getXh());
        session.removeAttribute("login");
        session.invalidate();
        return "login";
    }

    @RequestMapping("/page")
    public String page(Integer start,
                       @RequestParam(value = "number", defaultValue = "1") Integer number,
                       Model model, HttpSession session){
        if(number<0 || number==null){
            number=1;
        }
        int row = 3;
        start = (number-1)*row;
//        int maxPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        List<User> users = userService.queryByPage(start, row);
        model.addAttribute("users", users);
        List<Login> login = (List<Login>)session.getAttribute("login");
        Integer count =(Integer) session.getServletContext().getAttribute("count");
        String name = login.get(0).getName();
        model.addAttribute("name", name);
        model.addAttribute("count", count);
        int pageNum = number;

        model.addAttribute("pageNum", pageNum);
        return "page";
    }
}
